#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <unistd.h>
#include <string.h>
#include <limits.h>

#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>

#ifndef UTIL_H
#define UTIL_H

int get_user_count() {
    char* root = getenv("RELAT_ROOT");

    int count = 0;
    DIR* dirp;
    struct dirent* entry;

    if ((dirp = opendir(root)) == NULL) {
        perror("could not open root dir");
        exit(-1);
    }

    while ((entry = readdir(dirp)) != NULL) {
        char entry_path[256];
        sprintf(entry_path, "%s/%s", root, entry->d_name);

        struct stat* entry_stat;
        if (stat(entry_path, entry_stat) != 0) {
            perror("Could not read stats from entry");
            exit(-1);
        }

        if (!S_ISDIR(entry_stat->st_mode)) {
            continue;
        }

        // TODO: better check whether directory is really a user
        if (entry->d_namlen < 3) {
            continue;
        }

        count++;
    }

    return count;
}

unsigned long get_unix_timestamp() {
    struct timeval tv;
    gettimeofday(&tv, NULL);

    return (unsigned long)(tv.tv_sec) * 1000 + (unsigned long)(tv.tv_usec) / 1000;
}

void create_unit(char* user, char* unit, float x, float y) {
    char* root = getenv("RELAT_ROOT");

    char unit_directory[256];
    sprintf(unit_directory, "%s/%s/%s", root, user, unit);
    if (mkdir(unit_directory) != 0) {
        perror("mkdir failed");
        exit(-1);
    }
    
    char unit_pos_file_name[256];
    sprintf(unit_pos_file_name, "%s/%s/%s/position", root, user, unit);
    FILE* unit_pos_file;
    if ((unit_pos_file = fopen(unit_pos_file_name, "w")) == NULL) {
        perror("could not create position file for unit");
        exit(-1);
    }

    fprintf(unit_pos_file, "%.3f %.3f %.3f\n", x, y, 0.0f);
    fclose(unit_pos_file);

    char unit_move_file_name[256];
    sprintf(unit_move_file_name, "%s/%s/%s/move", root, user, unit);
    FILE* unit_move_file;
    if ((unit_move_file = fopen(unit_move_file_name, "w")) == NULL) {
        perror("could not create move file for unit");
        exit(-1);
    }

    fprintf(unit_move_file, "%ul %ul %.3f %.3f %.3f", 0l, ULONG_MAX, 0.0f, 0.0f, 0.0f);
}

#endif
